package com.example.xuetang;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

	 


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.example.zhuye.ZhuyeActivity;
import com.example.xuetang.ActivityStackManagerUtils;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.example.xuetang.HttpUtils;
 
	
public class MainActivity extends Activity implements OnClickListener {
	private EditText userText;
	private EditText passText;
	private Button denglu,wangji;
	private Button zhuce;
	private CheckBox rem_pw, auto_login;
	private String username,password;
	private SharedPreferences sp,sp2;
	public Editor editor,editor2;
	Dialog dialog;
 

    @Override
    protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    setContentView(R.layout.activity_main);
    wangji = (Button)findViewById(R.id.wangji);
    wangji.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent_wangji=new Intent();
			intent_wangji.setClass(MainActivity.this, Wangjimima.class);
			startActivity(intent_wangji);
		}
	});
    
    initWidget();
}
   
    public void initWidget()
    {
		sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);//不用于显示
		editor = sp.edit();
		sp2 = this.getSharedPreferences("userInfo2", Context.MODE_PRIVATE);//用于显示
		editor2 = sp2.edit();
    	userText = (EditText) findViewById(R.id.login_user_edit);
		passText = (EditText) findViewById(R.id.login_passwd_edit);
		username = userText.getText().toString();
		password = passText.getText().toString();
		
		rem_pw = (CheckBox) findViewById(R.id.jizhumima);
		auto_login = (CheckBox) findViewById(R.id.zidongdenglu);
		
		denglu = (Button) this.findViewById(R.id.denglu);
		zhuce = (Button) this.findViewById(R.id.zhuce);
		
		
		
		
		//判断记住密码多选框的状态
	      if(sp.getBoolean("ISCHECK", false))
	        {
	    	  //设置默认是记录密码状态
	          rem_pw.setChecked(false);
	          userText.setText(sp.getString("USER_NAME", ""));
	          passText.setText(sp.getString("PASSWORD", ""));
	       	  //判断自动登陆多选框状态
	       	  if(sp.getBoolean("AUTO_ISCHECK", false))
	       	  {
	       		     //设置默认是自动登录状态
	       		     auto_login.setChecked(false);
	       		    //跳转界面
	       		  if(checkEdit())
	              {
	                  login();
	              }  
					
	       	  }
	        }
	      
	      
	      //监听记住密码多选框按钮事件
			rem_pw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
					if (rem_pw.isChecked()) {
	                    
						System.out.println("记住密码已选中");
						sp.edit().putBoolean("ISCHECK", true).commit();
						
					}else {
						
						System.out.println("记住密码没有选中");
						sp.edit().putBoolean("ISCHECK", false).commit();
						
					}

				}
			});
			
			//监听自动登录多选框事件
			auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
	            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
					if (auto_login.isChecked()) {
						System.out.println("自动登录已选中");
						sp.edit().putBoolean("AUTO_ISCHECK", true).commit();

					} else {
						System.out.println("自动登录没有选中");
						sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
					}
				}
			});
			
			denglu.setOnClickListener(this);
			zhuce.setOnClickListener(this);   
    }
     
    @Override
    public void onClick(View v) 
    {
        // TODO Auto-generated method stub
        switch(v.getId())
        {
        case R.id.denglu:
            if(checkEdit())
            {
                login();
            }             
            break;
        case R.id.zhuce:
            Intent intent2=new Intent(MainActivity.this,RegisterActivity.class);
            startActivity(intent2);                     
            break;
        }
    }
     
    private boolean checkEdit()
    {   
        if(userText.getText().toString().trim().equals(""))
        {
            Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
        }
        else if(passText.getText().toString().trim().equals(""))
        {
            Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
        }
        else
        {
            return true;
        }
		return false;     
    }

    private String query(String username,String password) {
    	OutputStream outSream=null;
    	BufferedOutputStream bufoutput=null;
    	BufferedReader in=null;

    		String pathUrl = "http://1.teachapplication.sinaapp.com/servlet/LoginAction";
    		String writer="{'username':'"+username+"','password':'"+password+"'}";
    		return HttpUtils.httpconnect(pathUrl,writer);
		} 
    
    private void login()
    {
     	EditText userText = (EditText) findViewById(R.id.login_user_edit);
		EditText passText = (EditText) findViewById(R.id.login_passwd_edit);
		username = userText.getText().toString();
		password = passText.getText().toString();
		
		//记住用户名、密码、
		if(rem_pw.isChecked())
		{
		  
		  editor.putString("USER_NAME", username);
		  editor.putString("PASSWORD",password);
		  editor.commit();
		}
		if(IsConnection())
		{
			dialog = ProgressDialog.show(MainActivity.this, "玩转学堂",  "正在登陆 …", true, true);
			String result=query(username, password);
			if(result.contains("success"))
			{//学生登陆
				editor.putString("LEIXING", "stu");//若是学生登陆，将LEIXING保存为stu，在后面判断LEIXING就知道是老师
													//还是学生登陆的
				editor.putString("now_username", username); 
				editor2.putString("Password", password);
				editor2.putString("now_username", username); 
				editor.commit();
				editor2.commit();
				Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
	            Intent intent_stu=new Intent(MainActivity.this,ZhuyeActivity.class);
	            startActivity(intent_stu);
	            finish();
			}else //教师登陆
				if (result.contains("teacher")) {
					editor.putString("LEIXING", "tea");
					editor.putString("now_username", username); 
					editor2.putString("Password", password);
					editor2.putString("now_username", username); 
					editor.commit();
					editor2.commit();
					Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
		            Intent intent_tea=new Intent(MainActivity.this,ZhuyeActivity.class);
		            startActivity(intent_tea);
		            finish();
			}
			else
			{   
			    passText.setText("");
				Toast.makeText(MainActivity.this, "登录失败！", Toast.LENGTH_SHORT).show();
			}
		}
		else//网络没连接
		{
			Toast.makeText(MainActivity.this, "请检查网络连接！", Toast.LENGTH_SHORT).show();
		}
		
    	// Intent intent=new Intent(MainActivity.this,ZhuyeActivity.class);
     //  startActivity(intent);
       // finish();
    }	
    //判断网络是否已连接
    public boolean IsConnection()
	{
		ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);  
		boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();  
		boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); 
		if(wifi|internet){  
		    return true;

		}else{  
		    
			return false;
		}  
	}
}       




